package com.app.dao;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.app.dao.entity.BaseEntity;

public abstract class BaseDAO<T_ID extends Serializable, T_ENTITY extends BaseEntity> {

	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}

	protected static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	protected static Session getSession() {
		return getSessionFactory().getCurrentSession();
	}

	public static void beginTransaction() {
		getSession().beginTransaction();
	}

	public static void commiteTransaction() {
		if (getSession().isOpen() && getSession().getTransaction().isActive()) {
			getSession().getTransaction().commit();
			getSession().close();//
   
		}
	}

//	public static void closeTransaction() {
//        getSession().close();
           
	//}

	public static void rollbackTransaction() {
		if (getSession().isOpen() && getSession().getTransaction().isActive()) {
			getSession().getTransaction().rollback();
			getSession().close();//
		}
	}

	public void saveOrUpdate(T_ENTITY entity) {
		entity.setLastUpdate(new Date());
		getSession().saveOrUpdate(entity);
	}

	public abstract T_ENTITY findByID(T_ID id);

}
